<template>
    <div class="login-cb-wrapper">
        <div class="wrap">
            <div class="icon">
                <i class="img " :class="{loading}"></i>
            </div>
            <div class="msg">{{text}}</div>
            <div class="info">{{info}}</div>
        </div>
    </div>
</template>

<script>
    export default {
        name: "github",
        data() {
            return {
                code: '',
                text: '登陆中，请稍后...',
                info: '',
                loading: true
            }
        },
        created() {
            this.code = this.$utils.getUrlParam('code')
            const type = this.$utils.getUrlParam('state')
            if (type === 'login') {
                this.login()
            }
            if (type === 'bind') {
                this.bindUser()
            }
        },
        methods: {
            async login() {
                this.text = '登陆中，请稍后...'
                this.loading = true
                try {
                    let {data} = await this.$http.post('/v1/gitHubSignIn', {code: this.code})
                    this.$utils.store.set('token', data.token)
                    this.text = '登陆成功！'
                    window.opener.location.reload();
                    window.close()
                } catch (e) {
                    let {response: {data}} = JSON.parse(JSON.stringify(e))
                    this.text = '登陆失败！'
                    this.info = data.message
                }
                this.loading = false
            },
            async bindUser() {
                this.text = '绑定中，请稍后...'
                this.loading = true
                try {
                    let {data} = await this.$http.post('/v1/bindGitHub', {code: this.code})
                    this.text = '绑定成功！'
                    window.opener.location.reload();
                    window.close()
                } catch (e) {
                    let {response: {data}} = JSON.parse(JSON.stringify(e))
                    this.text = '绑定失败！'
                    this.info = data.message
                }
                this.loading = false
            }
        }
    }
</script>
